package at.fhj.itm;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener, OnKeyListener, OnItemClickListener {
	
	private TextView enterTask;
	private DBAccess dbAccess;
	private ListView list;
	private SimpleCursorAdapter adapter;
	private Cursor cursor;
	private SimpleDateFormat datumFormat;
	private Button btnAddTask;
	
	private static int TAKE_PICTURE = 1;
	private Uri outputFileUri;

	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        
        //Button to create a task
        btnAddTask = (Button) findViewById(R.id.btnAddTask);
        btnAddTask.setOnClickListener(this);
        
        enterTask = (TextView)findViewById(R.id.editText_enterTask);
        enterTask.setOnClickListener(this);
        enterTask.setOnKeyListener(this);
  
        String sql = "CREATE TABLE freunde (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
			         "taskName VARCHAR(20) NOT NULL, " +
			         "notes VARCHAR(20) , " +       
			         "dueDate DATE)";

		dbAccess     = new DBAccess(this, "todolist.dat", sql);
		
		datumFormat  = new SimpleDateFormat("dd.MM.yyyy");
		cursor       = dbAccess.createListViewCursor(); 
		
		list = (ListView) this.findViewById(R.id.listView1);
		list.setOnItemClickListener(this);
		
		
		String[] columns = new String[]{ "taskName", "notes", "dueDate"}; // 
		int[] views      = new int[]{ R.id.textViewName, R.id.textViewNote, R.id.textViewDate};
		adapter = new SimpleCursorAdapter(this, R.layout.data, cursor, columns, views);
		
		adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
			
		public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
		
		if (columnIndex == 3) {
			try {
				long datum = cursor.getLong(columnIndex); 
		
				if(datum != 0) {
					String str = datumFormat.format(new Date(datum));
					TextView anzeige = (TextView) view;
					anzeige.setText(str);
					return true; 
				}
		}
			catch(Exception ex) {}
			}
				return false; 
			}
		});
		
		list.setAdapter(adapter);
             
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        refresh();
    }

	@Override
	public void onClick(View v) {
		enterTask.setText("");
		//starts the TaskAktivity to add/edit a task
		if(btnAddTask.isPressed()){
			Intent intent = new Intent(this, TaskActivity.class);
			startActivity(intent);
		}
		
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
	            (keyCode == KeyEvent.KEYCODE_ENTER)) {
	          // Perform action on key press
			String taskName       = enterTask.getEditableText().toString();
			String notes    = "no notes";
			String datumString = "12.12.2011";
			Date datum;
			
			try {
               datum = datumFormat.parse(datumString);
			}
			catch(Exception x) {
				datum = null;
			}
			
			Bean record = new Bean(taskName, notes, datum);
			dbAccess.insertData(record);
			refresh();				
			
			Toast t = Toast.makeText(this, "task entered", Toast.LENGTH_LONG);
			t.show();
	          return true;
		}
		else {
			return false;
	    }
	}
	
	private void refresh() {
		if(cursor != null) {
			cursor.close();
		}
		
		cursor = dbAccess.createListViewCursor();
		adapter.changeCursor(cursor);
	}


	@Override
	protected void onDestroy() {
		if(cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
    	if(dbAccess != null) {
			dbAccess.close();
		}
		
		super.onDestroy();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.help:     try {
									Intent intent = new Intent(Intent.ACTION_VIEW);
									intent.setData(Uri.parse("http://2do4u.robertray.at"));
									startActivity(intent);
								} catch (Exception e) {
									Toast.makeText(this, "Website not available at the moment!", Toast.LENGTH_LONG).show();
								}
								return true;
								
	        		
	        	
	        case R.id.cam:     	try {
									Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
									File file = new File(Environment.getExternalStorageDirectory(),
											"test.jpg");
					
									outputFileUri = Uri.fromFile(file);
									intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
									startActivityForResult(intent, TAKE_PICTURE);
								} catch (Exception e) {
									Toast.makeText(this, "Kamera konnte nicht gestartet werden", Toast.LENGTH_LONG).show();
								}
								return true;
	    }
	    return false;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		
//		String selectedItem = (String) list.getItemAtPosition(arg2).toString();
//		Toast t = Toast.makeText(this, selectedItem, Toast.LENGTH_LONG);
//		t.show();

//		Object o = adapter.getItem(arg2);
//		String keyword = o.toString();
//		Toast t = Toast.makeText(this, keyword, Toast.LENGTH_LONG);
//		t.show();
		
		Object o2 = adapter.getView(arg2, arg1, arg0);
		String key = o2.toString();
		Toast t = Toast.makeText(this, key, Toast.LENGTH_LONG);
		t.show();
	}
	
	
	
	
	
}